package com.mccree.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.out.println("channel:"+ctx.channel()+";pipeline:"+ctx.pipeline()+"；通过pipeline获取channel:"+ctx.pipeline().channel());

        System.out.println("当前ctx的handler"+ctx.handler());

        //判断msg是不是http请求
        if (msg instanceof HttpRequest){
            System.out.println("ctx类型="+ctx.getClass());
            System.out.println("pipeline---->hashCode="+ctx.pipeline().hashCode()+";handler----->hashCode:"+this.hashCode());
            System.out.println("msg类型:"+msg.getClass());
            System.out.println("客户端地址:"+ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest)msg;
            //获取uri，过滤指定的资源
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了favicon，不做响应");
                return;
            }
            //回复信息给浏览器

            ByteBuf byteBuf = Unpooled.copiedBuffer("Hello,我是服务器", CharsetUtil.UTF_8);

            //构造一个http的响应,即httpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,byteBuf);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

            //返回response
            ctx.writeAndFlush(response);
        }
    }
}
